#pragma once
#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <cstring>
#include "Log.hpp"
#define BUFFER_SIZE 1024
#define DEFAULT_PROT 8888

using namespace LogModule;

class UDPClient
{
public:
    UDPClient(const std::string &ip, in_port_t port)
        : _server_addr_len(sizeof(_server_addr))
    {
        _server_addr.sin_addr.s_addr = inet_addr(ip.c_str());
        _server_addr.sin_family = AF_INET;
        _server_addr.sin_port = htons(port);

        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if (_sockfd < 0)
        {
            LOG(LogLevel::FATAL) << "socket: 套接字创建失败! ";
            exit(errno);
        }
        LOG(LogLevel::INFO) << "UDPClient: UDP套接字(sockfd=" << _sockfd << ")创建成功";
    }
    ~UDPClient()
    {
        close(_sockfd);
    }
    UDPClient(const UDPClient&) = delete;
    UDPClient& operator=(const UDPClient&) = delete;
    void Start()
    {
        std::string message;
        char buffer[BUFFER_SIZE];
        while (true)
        {
            std::cout << "Send to Server# ";
            std::getline(std::cin, message);
            sendto(_sockfd, message.c_str(), strlen(message.c_str()), 0, (struct sockaddr *)&_server_addr, _server_addr_len);
            ssize_t n = recvfrom(_sockfd, buffer, sizeof(buffer) - 1, 0, (struct sockaddr *)&_server_addr, &_server_addr_len);
            if (n > 0)
            {
                buffer[n] = 0;
                std::cout << "Server Message# " << buffer << std::endl;
            }
        }
    }

private:
    int _sockfd;
    struct sockaddr_in _server_addr;
    socklen_t _server_addr_len;
};